package com.tanhua.server.interceptor;

import com.tanhua.pojo.User;
import com.tanhua.server.service.UserService;
import com.tanhua.utils.NoAuthorization;
import com.tanhua.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {


    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //静态资源不拦截
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //判断是否包含Authorization注解，如果包含，直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }

        //从请求头中取出token
        String token = request.getHeader("Authorization");
        if (null != token) {
            User user = userService.queryUserByToken(token);
            if (null != user)
                UserThreadLocal.set(user);
            return true;
        }

        //无权限
        response.setStatus(401);

        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
